import pandas as pd
import csv

apiFile = pd.read_csv("data/api_nodes_estimator.csv", encoding='utf-8')
edgeFile = pd.read_csv("data/m-a_edges.csv", encoding='utf-8')

apiDf = pd.DataFrame(apiFile)
edgeDf = pd.DataFrame(edgeFile)

mash_api_Dict = {}  # 二维字典，存储各mash调用不同api的数量
api_c_Dict = {}  # 按url存储api类别

for apiName, apiC in zip(apiDf['url'], apiDf['c']):
    api_c_Dict[apiName] = apiC  # 存入api类别

for mashName, apiName in zip(edgeDf['source'], edgeDf['target']):
    if not api_c_Dict.get(apiName):
        continue

    if not mash_api_Dict.get(mashName):  # 定义二维字典value为字典类型
        mash_api_Dict[mashName] = {}

    mash_api_Dict[mashName][apiName] = api_c_Dict[apiName]

# for x in mash_api_Dict.keys():
#     if len(mash_api_Dict[x]) < 2:
#         del mash_api_Dict[x]

resList = []
for x in mash_api_Dict.keys():
    for y in mash_api_Dict[x].keys():
        for z in mash_api_Dict[x].keys():
            if y != z and mash_api_Dict[x][y] == mash_api_Dict[x][z]:
                tmp = [y, z, mash_api_Dict[x][y]]
                resList.append(tmp)

file = open('result/api_api_c.csv', 'a', newline='')  # 存入文件中
writer = csv.writer(file)
for row in resList:
    writer.writerow(row)
file.close()
